package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import cn.com.elite.PropertiesUtil
import com.elite.groovy.util.Util
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.util.DigestUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiTdxAddTask*
 * @Description:泰迪熊 名单推送*
 * @remak ：任务追加接口*
 * @author: TH*
 * @date 2023-10-12 11:11:00
 *
 */
public  class apiTdxAddTask implements ServiceBackInvoke{
    private static final Log log = LogFactory.getLog(apiTdxAddTask.class);
    public static long TimeMillis = System.currentTimeMillis();

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        JSONObject result = new JSONObject();
        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //获取接口调用方式及参数
        String GetMethod=httpServletRequest.getMethod();
        log.debug("[GetMethod]:"+GetMethod);
        String inData="";
        if (GetMethod.equals("GET")){
            inData=httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]"+inData);
        }else {
            InputStreamReader reader=new InputStreamReader(httpServletRequest.getInputStream(),"UTF-8");
            BufferedReader iny=new BufferedReader(reader);
            String line;
            while ((line=iny.readLine())!=null){
                inData+=line;
            }
            log.debug("[原始Post请求参数：]"+inData);

        }
        log.debug("[调用请求信息：]"+inData)

        if (KHUtil.isNull(inData)){
            log.debug("入参为空-无法完成操作！");
            result.put("code",-2)
            result.put("message","入参为空-无法完成操作！")
            return  result.toString();
        }
        try {
            //解析Json
            JSONObject inJson =JSONObject.fromObject(inData);
            def Taskid=GetJV(inJson ,"taskid");//任务ID  -必填
            def Taskname=GetJV(inJson ,"Taskname");//任务name  -必填
            def custlistname=GetJV(inJson,"custlistname");//批次号   -必填
            def assnum=GetJV(inJson ,"assnum");//分配数量  -必填
            def handleby_id=GetJV(inJson ,"handleby_id");//追加人  -必填
            def rolegroup_id=GetJV(inJson,"rolegroup_id");//追加组  -必填
            def staff_id=GetJV(inJson,"staff_id");//人
            def rolegroupid=GetJV(inJson,"rolegroupid");//组
            int isflag= GetJV(inJson,"isflag") as int;//1.代表泰迪熊追加界面,2.代表泰迪熊互损界面

            def queue= GetJV(inJson,"queue");//技能组
            List<Map<String, Object>> selectExits;
            if (isflag==1){
                log.debug("追加界面调用");
            String selectSQL = '''
                        Select ob.objective_Guid,
                        s.staff_id,
                        c.Customername || ',' || ob.objective_Guid,
                        case
                          when c.Mobile is not null then
                           c.Mobile
                          when c.tel_1 is not null then
                           c.tel_1
                          when c.atel_1 is not null then
                           c.atel_1
                          when c.atel_2 is not null then
                           c.atel_2
                          when c.atel_3 is not null then
                           c.atel_3
                          when c.Atel_4 is not null then
                           c.atel_4
                        end as mobile,
                        s.staffname,
                        s.stringfield4,
                        s.stringfield5,
                        ob.handlegroup_id,
                        case
                          when ob.attempt = 0 then
                           '首拨任务'
                          when ob.expectstarttime is not null and ob.attempt != 0 then
                           '预约任务'
                        end as taskname,
                        to_char(sysdate, 'yyyymmdd') as datetime,
                        o.custlistname,
                        c.customername,
                        T2.customer_guid
                   From elitetask ob
                   Left Join Customer T2
                     On ob.Customer_Guid = T2.Customer_Guid
                   Left Join Customer c
                     On c.Customer_Guid = T2.Parent_Guid
                   Left join objective o on o.objective_Guid=ob.objective_Guid
                   Left Join staff s
                     On s.staff_id = ob.handleby_id
                  Where ob.obflag = 1
                  and o.handleby_id IS NULL
                  and ob.custlistname=?
                  and ob.handlegroup_id=?
                    and c.Mobile is not null
                    and   c.Customername is not null 
                   and EXISTS(
                   select tc.CUSTLIST_XXX from TDX_CUSTLIST tc
                   where  tc.CUSTLIST_XXX=ob.custlistname
                         )
                  and rownum <= ?
                        ''';

            selectExits = jt.queryForList(selectSQL,custlistname,rolegroup_id,assnum);
            }else if (isflag==2){
              log.debug("呼损界面调用");
           String selectsql='''
                    Select ob.objective_Guid,
                        s.staff_id,
                        c.Customername || ',' || ob.objective_Guid,
                        case
                          when c.Mobile is not null then
                           c.Mobile
                          when c.tel_1 is not null then
                           c.tel_1
                          when c.atel_1 is not null then
                           c.atel_1
                          when c.atel_2 is not null then
                           c.atel_2
                          when c.atel_3 is not null then
                           c.atel_3
                          when c.Atel_4 is not null then
                           c.atel_4
                        end as mobile,
                        s.staffname,
                        s.stringfield4,
                        s.stringfield5,
                        ob.handlegroup_id,
                        case
                          when ob.attempt = 0 then
                           '首拨任务'
                          when ob.expectstarttime is not null and ob.attempt != 0 then
                           '预约任务'
                        end as taskname,
                        to_char(sysdate, 'yyyymmdd') as datetime,
                        o.custlistname,
                        c.customername,
                        T2.customer_guid
                   From elitetask ob
                   Left Join Customer T2
                     On ob.Customer_Guid = T2.Customer_Guid
                   Left Join Customer c
                     On c.Customer_Guid = T2.Parent_Guid
                   Left join objective o on o.objective_Guid=ob.objective_Guid
                   Left Join staff s
                     On s.staff_id = ob.handleby_id
                  Where ob.obflag = 1
                    and c.Mobile is not null
                    and   c.Customername is not null 
                   and EXISTS(
                 SELECT 
                tcl.objective_guid
                FROM tdx_call_loss tcl
               WHERE tcl.objective_guid=o.objective_guid
               AND tcl.taskid=?
                    )
                  and rownum <= ?
                   ''';
                selectExits = jt.queryForList(selectsql,custlistname,assnum);

                //删除呼损表数据
                String delsql=''' DELETE FROM tdx_call_loss WHERE  taskid=?'''
                jt.update(delsql,custlistname);


            }



            String str = String.valueOf(TimeMillis);
            String IV_SEED = DigestUtils.md5DigestAsHex(str.getBytes());
            JSONObject obJson =new JSONObject();
            JSONObject toJson=new JSONObject();
            JSONArray  arr =new JSONArray();
            JSONObject obj2=new JSONObject();
            if (selectExits.size() > 0) {
                for (int i=0; i < selectExits.size(); i++) {
                    Map selectExitsm = selectExits.get(i);
                    obj2.put("EXTEND1",selectExitsm.get("objective_Guid"));
                    obJson.put("name",selectExitsm.get("customername").toString());
                    obJson.put("phone",selectExitsm.get("mobile").toString());
                    obJson.put("extendFields",obj2)
                    arr.add(obJson);
                }
                toJson.put("taskId",Taskid);
                toJson.put("customers",arr);
                log.debug("【泰迪熊】追加接口请求参数："+toJson.toString());

                //调用追加接口
                String  resu = push_create(eliteBean,jt, toJson.toString());
                JSONObject jbm=JSONObject.fromObject(resu);
                result.put("code",GetJV(jbm,"code"));
                result.put("msg", GetJV(jbm,"message"));


                if (GetJV(result,"code")=="200"){

                    log.debug("【泰迪熊】追加名单处理完成返回结果:" + result.toString());

                    for (int b=0; b < selectExits.size(); b++) {
                        Map selectExitsm = selectExits.get(b);
                        //修改OBJECTIVE 标识状态
                        String upstate='''
                                      Update OBJECTIVE
                                      Set 
                                      STRINGFIELD5='ZJTDX',
                                      handleby_id=?,
                                      handlegroup_id=?
                                       where OBJECTIVE_GUID=?
                                     ''';
                        jt.update(upstate,staff_id,rolegroupid,selectExitsm.get("objective_guid"));

                        //修改Elitetask标识状态
                        String upstate3='''
                                      Update Elitetask
                                      Set 
                                      handleby_id=?,
                                         handlegroup_id=?
                                       where OBJECTIVE_GUID=?
                                     ''';
                        jt.update(upstate3,staff_id,rolegroupid,selectExitsm.get("objective_guid"));

                        //修改customer 标识状态
                        String upstate2='''
                                      Update CUSTOMER
                                      Set 
                                      STRINGFIELD15='ZJTDX'
                                       where CUSTOMER_GUID=?
                                     ''';
                        jt.update(upstate2,selectExitsm.get("customer_guid"));

                                String pushlisthis = ''' 
                                          insert 
                                          into 
                                          TDX_PUSH_LIST
                                          (
                                          REC_GUID,
                                          CREATEDDATE,
                                          TASKID,
                                          TASKNAME,
                                          CUSTOMERNAME,
                                          MOBILE,
                                          STAFF_ID,
                                          QUEUE,
                                          OBJECTIVE_GUID,
                                          custlistname,
                                          rolegroup_id,
                                          remark
                                          ) 
                                          values
                                          (
                                          sys_guid(),
                                          sysdate,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           '追加任务推送'
                                            )
                                            ''';

                        jt.update(
                                pushlisthis,
                                Taskid,
                                Taskname,
                                selectExitsm.get('customername'),
                                selectExitsm.get('mobile'),
                                staff_id,
                                queue,
                                selectExitsm.get("objective_guid"),
                                selectExitsm.get("custlistname"),
                                selectExitsm.get("handlegroup_id")
                        );

                    }




                }else{
                    result.put("code", -1);
                    result.put("msg", jbm.toString());
                    log.error("【泰迪熊】追加异常：");
                }





            } else {
                result.put("code", 1);
                result.put("msg", "无可推送名单");
            }




        }catch (Exception e) {
            result.put("code", -1);
            result.put("msg", e.getMessage());
            log.error("【泰迪熊】追加异常："+e.getMessage());
        }


        log.debug("【泰迪熊】追加名单处理完成返回结果:" + result.toString());

        return result.toString();
    }

    public static String   push_create(EliteBean eliteBean,JdbcTemplate jt,String inobj) {
        String sql = "select WEBSERVICEURL From sysc_interface where WEBTYPE='ZJ_TDX'";
        List<Map<String, Object>> createlist = jt.queryForList(sql)
        JSONObject jb = new JSONObject();
        if (createlist.size() > 0) {
            Map createmap = createlist.get(0)
            String url = createmap.get("WEBSERVICEURL");
            PropertiesUtil cfg = new PropertiesUtil();
            String proxyIp = cfg.readValue("QingNiu.ProxyIP");
            String proxyPort = cfg.readValue("QingNiu.ProxyPort");

            JSONObject obj = new JSONObject();
            JSONArray agentJids = new JSONArray()
            JSONArray customers = new JSONArray();

            String sql2 = "select WEBSERVICEURL From sysc_interface where WEBTYPE='groovy'";
            List<Map<String, Object>> groovyUrl = jt.queryForList(sql2)
            String geturl = groovyUrl.get(0).get("WEBSERVICEURL");

            String tokenUrl = geturl.toString() + "apiTdxToken";

            //调用内部接口获取泰迪熊Token
            String tokenbody = Util.doHttpPost(tokenUrl, "", "UTF-8", "20000" as int, 0, "");

            JSONObject body = JSONObject.fromObject(tokenbody);
            if (body.getInt("code") == 200) {
                String token = GetJV(body, "token");
                //设置请求表头
                Map<String, String> TokenParams = new HashMap<String, String>();
                TokenParams.put("X-Token", token);
                TokenParams.put("Content-Type", "application/json");
                String orgName = KHDBConfig.getParam(eliteBean, "TDXQID", "");//orgName	企业id
                String appName = KHDBConfig.getParam(eliteBean, "TDXAID", "");//appName	appId

                String createUrl = url.toString() + "/rest/" + orgName.toString() + "/" + appName.toString() + "/cc/mmcTask/append";//请求URL拼接
                JSONObject jbm=JSONObject.fromObject(inobj);
                log.debug("【泰迪熊创建任务】接口请求URL：" + createUrl.toString());
                log.debug("【泰迪熊请求任务】接口请求参数：" + jbm.toString());
                String create_result = Util.doHttpPostUseHead1(createUrl, jbm.toString(), "UTF-8", 20000, 0, TokenParams,"",proxyIp, proxyPort as int,true);

                jb=JSONObject.fromObject(create_result);

                log.debug("【泰迪熊创建任务】接口返回参数：" + jb.toString());

            }else{
                log.error("获取泰迪熊Token异常："+body.toString());
            }

        }


         return jb.toString();
    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

}
